<?php

namespace app\common\model;

use fast\Auth;
use think\Db;
use think\Exception;
use think\Model;
use think\Request;

class BuyRecord extends Model
{
    // 表名
    protected $name = 'buy_record';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
	protected $updateTime = false;
    // 追加属性
    protected $append = [
        'create_time_text',
	    'status_text',
	    'is_robot_text'
    ];
    

    const STATUS_Y = 1;
    const STATUS_N = 2;
    const STATUS_W = 0;
    
    public static $statusList = [
        self::STATUS_Y => '已中奖',
	    self::STATUS_N => '未中奖',
	    self::STATUS_W => '待开奖'
    ];
    

    public function getStatusTextAttr($value, $data) {
    	$value = $value?$value:$data['status'];
    	$list = self::$statusList;
    	return isset($list[$value])?$list[$value]:'';
    }
	
	const ROBOT_Y = 1;
	const ROBOT_N = 0;
	
	public static $robotList = [
		self::ROBOT_Y => '是',
		self::ROBOT_N => '否'
	];
	
	public function getIsRobotTextAttr($value, $data) {
		$value = $value ? $value : $data['is_robot'];
		$list = self::$robotList;
		return isset($list[$value]) ? $list[$value] : '';
	}

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
	
    
    public function user(){
    	return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
    }
	
	/**
	 * 计算创建订单
	 * @param $userId 用户ID
	 * @param string $operateType 操作类型 1计算价格 其它生成订单
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
    public function createOrder($userId, $operateType = '1') {
    	set_time_limit(0);
	    $type = input('post.type', 'cart');
	    $recordId = input('post.record_id', '', 'int');
	    $number = input('post.number', '', 'int');
	    $cardIds = input('post.cart_ids');
	    $datas = [];
	    if($type == 'goods') {
		    if (!$recordId || $recordId <= 0 || !$number || $number <= 0) {
			    $this->error = __('参数错误');
			    return false;
		    }
		
		    $goods = Db::name('goodsRecord')->alias('r')
			    ->join('goods g', 'r.goods_id = g.id', 'left')
			    ->field('r.id, r.total_number, r.buy_number, r.status, r.goods_id, g.sotre, g.price, g.goods_name')
			    ->find($recordId);
		    if (!$goods) {
			    $this->error = __('购买记录不存在');
			    return false;
		    }
		    $goods['number'] = $number;
		    $datas[] = $goods;
	    } else {
		    if(!$cardIds) {
			    $this->error = __('参数错误');
			    return false;
		    }
		    $ids = explode(',', $cardIds);
		    $datas = Db::name('cart')->alias('c')
			    ->join('goodsRecord r', 'c.goods_record_id = r.id', 'left')
			    ->join('goods g', 'r.goods_id = g.id', 'left')
			    ->where(['c.id' => ['in', $ids]])
			    ->field('r.id, r.total_number, r.buy_number, r.status, r.goods_id, g.sotre, g.price, g.goods_name, c.number')
			    ->select();
	    }
	    
	    if(!$datas) {
	    	$this->error = __('购买记录不存在');
	    }
	    
	    $recordModel = new GoodsRecord();
	    
	    $installDatas = [];
	    
	    $totalNumber = 0;
	    $totalAmount = 0;
	    
	    foreach($datas as $data) {
	    	if($data['status'] != $recordModel::STATUS_B) {
	    		$this->error = $data['goods_name'].__('该期数已结束购买');
	    		return false;
		    }
		    
		    $recNumber = $data['total_number']-$data['buy_number'];
	    	if($data['number'] > $recNumber){
	    		$this->error = $data['goods_name'].__('剩余购买次数为').$recNumber;
	    		return false;
		    }
		    
		    $noList = [];
	    	for ($i = 0; $i < $data['number']; $i ++) {
	    		$noList[] = 10000000+$i+$data['buy_number'];
		    }
		    
		    $totalNumber += $data['number'];
	    	$totalAmount += $data['number'] * \think\Config::get('oneAmount');
	    	
		    $installDatas[] = [
		    	'user_id' => $userId,
			    'goods_record_id' => $data['id'],
			    'number' => $data['number'],
			    'create_time' => time(),
			    'ip' => Request::instance()->ip(),
			    'no_list' => implode(',', $noList)
		    ];
	    }
	    
	    //计算价格
	    if($operateType == 1){
	        return [
	            'totalAmount' => $totalAmount,
		        'totalNumber' => $totalNumber,
		        'goods' => $datas,
	        ];
	    }
	    
	    $user = User::get($userId);
	    if($user['balance'] < $totalAmount) {
	    	$this->error = __('余额不足,当前余额').' 【'.$user['balance'].'】';
	    	return -1;
	    }
	   
	    $this->startTrans();
	    try {
	    	//添加订单
		    $res = $this->saveAll($installDatas);
		    if(!$res) {
		    	throw new Exception(__('添加订单出错'));
		    }
		
		    //添加流水
		    $fundModel = new FundsRecord();
		    $fundRes = $fundModel->addRecord($userId, $totalAmount,$user['balance'], $fundModel::ACCOUNT_TYPE_BALANCE, $fundModel::OPE_TYPE_LESS, $fundModel::TYPE_PAY_ORDER);
		    if(!$fundRes) {
		    	throw new Exception(__('添加资金流水出错'));
		    }
			   
		    //减少余额
		    $userRes = $user->setDec('balance', $totalAmount);
		    if(!$userRes) {
		    	throw new Exception(__('减少余额出错'));
		    }
	    	
		    //减少购物车
		    if($operateType != 1) {
		    	Db::name('cart')->where(['id' => ['in', $cardIds]])->update(['status' => Cart::STATUS_B]);
		    }
		    
		    
		    foreach($datas as $data) {
		    	if($data['buy_number'] + $data['number'] >= $data['total_number']) {
		    		//商品库存大于1，添加新期数
		    		if($data['sotre'] > 1) {
					    $newRes = $recordModel->createRecord($data['goods_id'], $data['price']);
					    if(!$newRes) {
					    	throw new Exception($data['goods_name'].'添加新期数出错');
					    }
				    }
				    
				    $time = time();
		    		$minu = date('i', $time);
		    		$openTime = strtotime(date('Y-m-d H:'.($minu+5).':s'));
				   
				    //更改期数状态
				    $recordRes = Db::name('goodsRecord')
					    ->where(['id' => $data['id']])
					    ->update([
					        'status' => $recordModel::STATUS_W,
						    'end_time' => $time,
						    'open_time' => $openTime,
						    'buy_number' => $data['total_number']
					    ]);
				    
				    if(!$recordRes) {
				    	throw new Exception(__('更改期数状态出错'));
				    }
				    
				    //减库存
				    $sotreRes = Db::name('goods')->where(['id' => $data['goods_id']])->setDec('sotre');
				    if(!$sotreRes) {
				    	throw new Exception(__('更改库存出错'));
				    }
			    } else {
				    //更改期数购买数量
				    $recordRes = Db::name('goodsRecord')
					    ->where(['id' => $data['id']])
					    ->setInc('buy_number', $data['number']);
				    if(!$recordRes) {
					    throw new Exception(__('更改期数状态出错'));
				    }
			    }
		    }
		    
	    	$this->commit();
	        return true;
	    } catch (Exception $e) {
	    	$this->rollback();
	    	$this->error = $e->getMessage();
	    	return false;
	    }
	    
    }
	
	
	/**
	 * 计算开奖号码
	 * @param $time 结束时间
	 * @param $number 购买人数
	 * @return int
	 */
    public function getOpenNo($time, $number) {
    	$orders = $this
		    ->where(['create_time' => ['egt', $time]])
		    ->sum('create_time');
    	
    	$no = ($orders%$number)+10000000;
    	return $no;
    	
    }
    
    
    public function createRobotOrder($record){
        //查找机器人用户
	    $users = Db::name('user')
		   ->where(['is_robot' => \app\admin\model\User::ROBOT_Y])
	        ->column('id');
	    
	    if(!$users) {
	    	$this->error = '没有机器人用户';
	    	return false;
	    }
	    
	    $userId = $users[array_rand($users)];
	    
	    $noList = $record['buy_number']+10000001;
	    $res = $this->isUpdate(false)->save([
		    'user_id' => $userId,
		    'goods_record_id' => $record['id'],
		    'number' => 1,
		    'no_list' => $noList,
		    'is_robot' => self::ROBOT_Y
	    ]);
	   
	    if($res) {
	    	return $noList;
	    }
	    return false;
    }
}
